/*
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-02 09:54:41
 * @LastEditTime: 2024-02-04 15:57:08
 */
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@g/router/index'
import useSettingsStore from '@g/store/modules/settings'
import useUserStore from '@g/store/modules/user'
import { useI18n } from 'vue-i18n'
import { ikStore } from 'iking-utils'
import { systemConfig } from '../../system.config'

const { remberRoute } = systemConfig

const excludeUrl = [
  '/server/scaffold/project/download',
  '/server/scaffold/module/download'
]
const toLogin = (statu = true) => {
  useUserStore().clearCache()
  const query = (statu && remberRoute)
    ? {
        redirect:
      router.currentRoute.value.path !== '/login'
        ? router.currentRoute.value.fullPath
        : undefined
      }
    : {}
  router.push({
    path: '/login',
    query
  })
  // location.href = `${location.href}`
}

const api = axios.create({
  baseURL:
    (import.meta.env.DEV && import.meta.env.VITE_OPEN_PROXY === 'true')
      ? '/api/'
      : import.meta.env.VITE_APP_API_BASEURL,
  timeout: 1000 * 60,
  responseType: 'json'
})

api.interceptors.request.use(async (request: any) => {
  // 全局拦截请求发送前提交的参数
  const settingsStore = useSettingsStore()
  const userStore = useUserStore()
  // 设置公共请求头
  if (request.headers) {
    request.headers['Accept-Language'] = settingsStore.settings.app.defaultLang
    request.headers.Authorization
      = userStore.token || ikStore.local.getItem(ELocal.TOKEN)
    if (userStore.isLogin) {
      const menuId = ikStore.local.getItem('menuid')
      request.headers['menu-id'] = menuId
      request.headers['X-TENANT']
        = userStore?.tenant?.code || ikStore.local.getItem(ELocal.TENANT)?.code
      request.headers['X-ORG']
        = userStore?.organiza?.select || ikStore.local.getItem(ELocal.ORGANIZA)?.select
    }
  }
  // 是否将 POST 请求参数进行字符串化处理
  if (request.method === 'post') {
    // request.data = JSON.stringify(request.data, {
    //   arrayFormat: 'brackets',
    // })
  }
  return request
})

api.interceptors.response.use(
  (response: any) => {
    // ElMessage.closeAll()
    /**
     * 全局拦截请求发送后返回的数据，如果数据有报错则在这做全局的错误提示
     * 假设返回数据格式为：{ code: 1, success: true, data: '' }
     * 规则是当 code 为 0 时表示请求成功，为 1 时表示接口需要登录或者登录状态失效，需要重新登录
     * 请求出错时 error 会返回错误信息
     */
    // response.data.status 兼容mock服务 - 不需要mock服务时可删除此判断
    if (
      response.status === 200
      || response.data.status === 1
      || response.data.code === 0
    ) {
      if (
        !excludeUrl.includes(response?.config?.url)
        && !response.data.success
      ) {
        // 这里做错误提示，如果使用了 element plus 则可以使用 Message 进行提示
        // ElMessage.error(response.data.msg)
        return Promise.resolve(response.data)
      }
    }
    else {
      // TODO：返回登录页的条件
      toLogin()
    }
    return Promise.resolve(response.data)
  },
  (error: any) => {
    ElMessage.closeAll()
    let message = error.message
    if (message === 'Network Error') {
      message = useI18n().t('code.netErr')
      ElMessage.warning('网络错误，请稍后重试')
    }
    else if (message.includes('timeout')) {
      message = useI18n().t('code.504')
      ElMessage.warning('请求超时，请稍后重试')
    }
    // 登录过期，返回登录页
    else if (message.includes('401')) {
      message = '登录失效, 即将返回登录页面'
      toLogin(false)
    }
    else if (message.includes('Request failed with status code')) {
      message = `请求[${error?.config?.url}]${message.substr(message.length - 3)}异常`
      ElMessage.warning(message)
    }

    // 请求错误统一返回对象
    return Promise.resolve({
      success: false,
      data: null,
      msg: message
    })
  }
)

export default api
